package com.xpec.c4.db.secure;

import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

/**
 * AES加密工具
 * 
 * @author Bany
 * 
 * @version 创建时间：2008-8-5 上午10:58:16
 * 
 */

public class SecUtil {

	private static byte[] keybytes = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36,
			0x37, 0x38, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38 };

	public static void main(String[] args) throws Exception {
		String e1 = encrypt("test");
		System.out.println(e1);
		String e2 = decrypt(e1);
		System.out.println(e2);
	}

	/**
	 * 加密
	 * @param value
	 * @return
	 */
	public static String encrypt(String value) {
		
		String s=null;

		int mode = Cipher.ENCRYPT_MODE;

		try {
			Cipher cipher = initCipher(mode);

			byte[] outBytes = cipher.doFinal(value.getBytes());

			s = String.valueOf(Hex.encodeHex(outBytes));
		} catch (Exception e) {
			e.printStackTrace();
		}

		return s;
	}

	/**
	 * 解密
	 * @param value
	 * @return
	 */
	public static String decrypt(String value) {

		String s = null;

		int mode = Cipher.DECRYPT_MODE;

		try {
			Cipher cipher = initCipher(mode);

			byte[] outBytes = cipher.doFinal(Hex.decodeHex(value.toCharArray()));

			s = new String(outBytes);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return s;
	}
	
	private static Cipher initCipher(int mode) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException{
		Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
		Key key = new SecretKeySpec(keybytes, "AES");
		cipher.init(mode, key);
		return cipher;
	}
}
